package com.koron.css2.serviceManage.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.koron.css2.ApplicationConfig;
import com.koron.css2.ServerInterface;
import com.koron.css2.serviceManage.bean.QuartzBean;
import com.koron.css2.serviceManage.bean.RequestBean;
import com.koron.css2.serviceManage.bean.UserInfoBean;
import com.koron.css2.serviceManage.mapper.QuartzMapper;
import com.koron.css2.serviceManage.queryBean.JobQueryBean;
import com.koron.css2.serviceManage.utils.JsonUtils;
import com.koron.util.Constant;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.koron.ebs.mybatis.SessionFactory;
import org.swan.bean.MessageBean;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

public class JobList implements ServerInterface{

	
	private Logger log = LogManager.getLogger(JobList.class);
	@Override
	public MessageBean<?> exec(SessionFactory factory, UserInfoBean userInfo, RequestBean req) {
		@SuppressWarnings("rawtypes")
		MessageBean<PageInfo> info = MessageBean.create(Constant.MESSAGE_INT_SUCCESS, "success", PageInfo.class);

		try {
			JobQueryBean bean = JsonUtils.objectToPojo(req.getData(), JobQueryBean.class);
			QuartzMapper mapper = factory.getMapper(QuartzMapper.class);

			PageHelper.startPage(bean.getPage(), bean.getPageCount());
			List<QuartzBean> list = mapper.selectList(bean, ApplicationConfig.getQuartzPrefix());
			for(QuartzBean quartz : list) {
				//转换日期格式
				if(quartz.getNextFireTime() != null)
					quartz.setNextFireTime(timeStampToTime(quartz.getNextFireTime()));
				if(quartz.getPrevFireTime() != null)
					quartz.setPrevFireTime(timeStampToTime(quartz.getPrevFireTime()));
				
				if("WAITING".equalsIgnoreCase(quartz.getTriggerState()))
					quartz.setStateName("等待");
				else if("PAUSED".equalsIgnoreCase(quartz.getTriggerState()))
					quartz.setStateName("暂停");
					else if("ACQUIRED".equalsIgnoreCase(quartz.getTriggerState()))
						quartz.setStateName("正常执行");
						else if("BLOCKED".equalsIgnoreCase(quartz.getTriggerState()))
							quartz.setStateName("阻塞");
							else if("ERROR".equalsIgnoreCase(quartz.getTriggerState()))
								quartz.setStateName("错误");
							else
								quartz.setStateName("");
			}						
			info.setData(new PageInfo<>(list));
		} catch (Exception e) {
			info.setCode(Constant.MESSAGE_INT_FAIL);
			info.setDescription(e.getMessage());
			logger.error(e.getMessage(), e);
		}
		return info;
	}
	


	/**
	 * 时间戳转换成日期格式字符串
	 * @param seconds 精确到秒的字符串
	 * @return
	 */
	public static String timeStampToTime(String seconds) {
		String format = "yyyy-MM-dd HH:mm:ss";
		SimpleDateFormat sdf = new SimpleDateFormat(format);
		return sdf.format(new Date(Long.valueOf(seconds)));
	}
}
